//
//  YLAddBookViewController.m
//  TheAddressBookDemo
//
//  Created by YangLei on 16/3/15.
//  Copyright © 2016年 YangLei. All rights reserved.
//

#import "YLAddBookViewController.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import <Contacts/Contacts.h>
#import <ContactsUI/ContactsUI.h>

#import "YLChineseString.h"
#import "YLAddBookTableViewCell.h"
#define WINTHSCREEN  ([UIScreen mainScreen].bounds.size.width)

@interface YLAddBookViewController ()
{
}
@property(nonatomic, strong)UISearchBar *theSearchBar;
@property(nonatomic, strong)UITableView *tablview;

@property(nonatomic, strong)UILabel * labelnoshouquan;//没有授权通讯录
@property(nonatomic, strong)UILabel * labelnosousuo;//没有搜索内容
@end

@implementation YLAddBookViewController
/**
 检测权限并作响应的操作
 */
- (void)__checkAuthorizationStatus
{
    //这里有一个枚举类:CNEntityType,不过没关系，只有一个值:CNEntityTypeContacts
    switch ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts])
    {
            //存在权限
        case CNAuthorizationStatusAuthorized:
            //获取通讯录
            NSLog(@"存在权限");
//            [self __obtainContacts:self.completeBlock];
            break;
            
            //权限未知
        case CNAuthorizationStatusNotDetermined:
            NSLog(@"权限未知");
            //请求权限
//            [self __requestAuthorizationStatus];
            break;
            
            //如果没有权限
        case CNAuthorizationStatusRestricted:
        case CNAuthorizationStatusDenied://需要提示
//            self.defendBlock();
            NSLog(@"没有权限");
            break;
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.labelnoshouquan];
    [self.view addSubview:self.labelnosousuo];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.theSearchBar];
    [self.view addSubview:self.tablview];
    [self filterContentForSearchText:@""];//查询所有
    CNContactStore *store = [[CNContactStore alloc] init];
    [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted == YES) {
            //keys with fetching properties
            NSArray *keys = @[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey,CNContactMiddleNameKey];
            NSString *containerId = store.defaultContainerIdentifier;
            NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
            NSError *error;
            NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
//            if (error) {
//                NSLog(@"error fetching contacts %@", error);
//            } else {
//                NSString *phone;
//                NSString *fullName;
//                NSString *firstName;
//                NSString *lastName;
//                UIImage *profileImage;
//                NSMutableArray *contactNumbersArray;
//                for (CNContact *contact in cnContacts) {
//                    // copy data to my custom Contacts class.
//                    firstName = contact.givenName;
//                    lastName = contact.familyName;
//                    if (lastName == nil) {
//                        fullName=[NSString stringWithFormat:@"%@",firstName];
//                    }else if (firstName == nil){
//                        fullName=[NSString stringWithFormat:@"%@",lastName];
//                    }
//                    else{
//                        fullName=[NSString stringWithFormat:@"%@ %@",firstName,lastName];
//                    }
//                    UIImage *image = [UIImage imageWithData:contact.imageData];
//                    if (image != nil) {
//                        profileImage = image;
//                    }else{
//                        profileImage = [UIImage imageNamed:@"person-icon.png"];
//                    }
//                    for (CNLabeledValue *label in contact.phoneNumbers) {
//                      phone = [label.value stringValue];
//                        if ([phone length] > 0) {
//                           [contactNumbersArray addObject:phone];
//                        }
//                    }
//                    NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys: fullName,@"fullName",profileImage,@"userImage",phone,@"PhoneNumbers", nil];
//                   [self.contactsArray addObject:personDict];
//                }
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [self.tableViewRef reloadData];
//                });
//            }
        }else
        {
            self.tablview.hidden = YES;
            self.theSearchBar.hidden = YES;
            self.labelnoshouquan.hidden = NO;
        }
    }];

}

-(UITableView *)tablview
{
    if (!_tablview) {
        _tablview = [[UITableView alloc]initWithFrame:CGRectMake(0, 64+40,self.view.frame.size.width, self.view.frame.size.height-64-40) style:UITableViewStylePlain];
        _tablview.backgroundColor = [UIColor whiteColor];
        //改变索引的颜色
        _tablview.sectionIndexColor = [UIColor redColor];
        //改变索引选中的背景颜色
        _tablview.sectionIndexTrackingBackgroundColor = [UIColor yellowColor];
        _tablview.dataSource = self;
        _tablview.delegate = self;
        _tablview.tableFooterView = [UIView new];
    }
    return _tablview;
}
-(UISearchBar *)theSearchBar
{
    if (!_theSearchBar) {
        _theSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 64, self.view.bounds.size.width, 40)];
        _theSearchBar.autocorrectionType = UITextAutocorrectionTypeNo;
        _theSearchBar.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;
        _theSearchBar.scopeButtonTitles = [NSArray arrayWithObjects:@"All",@"A",@"B",@"C",@"D" ,nil];
        _theSearchBar.showsScopeBar = YES;
        _theSearchBar.keyboardType = UIKeyboardTypeNamePhonePad;
        //    theSearchBar.showsBookmarkButton = YES;
        _theSearchBar.delegate = self;
    }
    return _theSearchBar;
}
- (UILabel *)labelnoshouquan
{
    if (!_labelnoshouquan) {
        _labelnoshouquan = [[UILabel alloc]initWithFrame:CGRectMake(0, 150,WINTHSCREEN, 40)];
        _labelnoshouquan.backgroundColor = [UIColor clearColor];
        _labelnoshouquan.textColor = [UIColor blackColor];
        _labelnoshouquan.textAlignment = NSTextAlignmentCenter;
        _labelnoshouquan.numberOfLines = 0;
        _labelnoshouquan.font = [UIFont systemFontOfSize:14.0];
        _labelnoshouquan.text  = @"没有权限访问通讯录，请前往设置允许应用访问通讯录";
        _labelnoshouquan.hidden = YES;
    }
    return _labelnoshouquan;
}
-(UILabel *)labelnosousuo
{
    if (!_labelnosousuo) {
        _labelnosousuo = [[UILabel alloc]initWithFrame:CGRectMake(0, 150,WINTHSCREEN, 30)];
        _labelnosousuo.backgroundColor = [UIColor clearColor];
        _labelnosousuo.textColor = [UIColor blackColor];
        _labelnosousuo.text  = @"没有您搜索的客户";
        _labelnosousuo.textAlignment = NSTextAlignmentCenter;
        _labelnosousuo.hidden = YES;
    }
    return _labelnosousuo;
}

#pragma mark-  IOS9 及以后调用的方法
/**
 IOS9 及以后调用的方法
 */
- (BOOL)requestContactAuthorizedAfterSystemVersionNine {
    
    CNAuthorizationStatus contactStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    
    NSString *authorizedMsg = @"";
    
   __block BOOL isAuthorized = NO;
    
    switch (contactStatus) {
        case CNAuthorizationStatusNotDetermined: {
            authorizedMsg = @"用户未确定是否授权";
            CNContactStore *contactStore = [[CNContactStore alloc]init];
            
           dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
            
            [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
                
                if (error) {
                    isAuthorized = NO;
#ifdef DEBUG
                    NSLog(@"contact 授权 error：%@",error.description);
                    
#endif
                }else if(granted == NO){
                    isAuthorized = NO;
                }else {
                    isAuthorized = YES;
                }
                
                dispatch_semaphore_signal(semaphore);
                
            }];
            
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            
            
        }
            break;
        case CNAuthorizationStatusRestricted:
            authorizedMsg = @"iOS 设备上一些许可配置阻止程序与通讯录数据库进行交互";
            isAuthorized = NO;
            break;
        case CNAuthorizationStatusDenied:
            authorizedMsg = @"用户明确的拒绝了你的程序对通讯录的访问";
            isAuthorized = NO;
            break;
        case CNAuthorizationStatusAuthorized:
            authorizedMsg = @"用户已经授权给你的程序对通讯录进行访问";
            isAuthorized = YES;
            break;
        default:
            authorizedMsg = @"default 未知信息";
            isAuthorized = NO;
            break;
    }

#ifdef DEBUG
    NSLog(@"在iOS 9及以上设备上，通讯录授权信息：%@ %d",authorizedMsg,isAuthorized);
#endif
    
    return isAuthorized;
    
    
}
- (void)filterContentForSearchText:(NSString*)searchText
{
    //如果没有授权则退出
    BOOL isAuthorized = [self requestContactAuthorizedAfterSystemVersionNine];
    if (!isAuthorized) {
        self.labelnoshouquan.hidden = NO;
        return ;
    }



    CNContactStore *store = [[CNContactStore alloc] init];
     NSArray *keys = @[CNContactNamePrefixKey,CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey,CNContactMiddleNameKey];
     NSString *containerId = store.defaultContainerIdentifier;
    NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
    NSError *error;
    if([searchText length]==0)
    {
        //查询所有
        self.listContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
               
//        self.listContacts = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));
        self.theSearchBar.placeholder = [NSString stringWithFormat:@"搜索客户（共%ld位）",self.listContacts.count];
        if (self.listContacts.count == 0)
        {
            self.theSearchBar.placeholder = @"无客户";
            self.tablview.hidden = YES;
            self.labelnosousuo.hidden = NO;
        }else
        {
            self.tablview.hidden = NO;
            self.labelnosousuo.hidden = YES;
        }
        NSMutableArray * arrlast = [NSMutableArray array];
        for (int i = 0; i < self.listContacts.count; i ++) {
            CNContact *contact = self.listContacts[i];
            
            NSString *firstName = contact.givenName;
            firstName = firstName != nil?firstName:@"";
            
            
            NSString *centerName = contact.middleName;
            centerName = centerName != nil?centerName:@"";
            
            NSString *lastName =  contact.familyName;
            
            lastName = lastName != nil?lastName:@"";
            
            NSString * lastStr = [NSString stringWithFormat:@"%@%@%@",lastName,centerName,firstName];
            //            NSLog(@"ffdfd%@",lastStr);
            if (lastStr) {
                [arrlast addObject:lastStr];
                
            }
            
            
        }
        
        //        NSLog(@"%@",arrlast);
        
        self.indexArray = [YLChineseString IndexArray:arrlast];
        self.letterResultArr = [YLChineseString LetterSortArray:arrlast];
        
        
    } else {
        //条件查询
        CNContactStore *store = [[CNContactStore alloc] init];
        // 检索条件
        NSPredicate *predicate = [CNContact predicateForContactsMatchingName:searchText];
        
        self.listContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:@[CNContactGivenNameKey,CNContactMiddleNameKey,CNContactFamilyNameKey] error:nil];
        

        if (self.listContacts.count == 0) {
            self.tablview.hidden = YES;
            self.labelnosousuo.hidden = NO;
        }else{
            
            self.tablview.hidden = NO;
            self.labelnosousuo.hidden = YES;
            
        }
        
        NSMutableArray * arrlast = [NSMutableArray array];
        for (int i = 0; i < self.listContacts.count; i ++) {
            CNContact *contact = self.listContacts[i];// ①第①行ABRecordRef thisPerson = CFBridgingRetain([self.listContacts objectAtIndex:[indexPath row]])语句是从NSArray*集合中取出一个元素，并且转化为Core Foundation类型的ABRecordRef类型。CFBridgingRelease(ABRecordCopyValue(thisPerson, kABPersonFirstNameProperty))语句是将名字属性取出来，转化为NSString*类型。最后CFRelease(thisPerson)是释放ABRecordRef对象。
            NSString *firstName = contact.givenName;
            firstName = firstName != nil?firstName:@"";
            
            
            NSString *centerName =contact.middleName;
            centerName = centerName != nil?centerName:@"";
            
            NSString *lastName =  contact.familyName;
            
            lastName = lastName != nil?lastName:@"";
            
            NSString * lastStr = [NSString stringWithFormat:@"%@%@%@",lastName,centerName,firstName];
            if (lastStr) {
                [arrlast addObject:lastStr];
                
            }
            
        }
        self.indexArray = [YLChineseString IndexArray:arrlast];
        self.letterResultArr = [YLChineseString LetterSortArray:arrlast];
    }
    [self.tablview reloadData];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.theSearchBar resignFirstResponder];
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    [self.theSearchBar resignFirstResponder];
    return YES;
}
#pragma mark –UISearchBarDelegate 协议方法
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    //查询所有
    [self filterContentForSearchText:self.theSearchBar.text];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [self filterContentForSearchText:searchText];
}
#pragma mark - UISearchDisplayController Delegate Methods
//当文本内容发生改变时候，向表视图数据源发出重新加载消息
- (BOOL)searchDisplayController:(UISearchController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString];
    //YES情况下表视图可以重新加载
    return YES;
}
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return self.indexArray;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSString *key = [self.indexArray objectAtIndex:section];
    return key;
}
//响应点击索引时的委托方法
//-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
//{
//    NSInteger count = 0;
//
//    NSLog(@"%@-%d",title,index);
//
//    for(NSString *character in self.indexArray)
//    {
//        if([character isEqualToString:title])
//        {
//            return count;
//        }
//        count ++;
//    }
//    return 0;
//}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.indexArray count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[self.letterResultArr objectAtIndex:section] count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 80;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
    /*
     kABPersonFirstNameProperty，名字
     
     kABPersonLastNameProperty，姓氏
     
     kABPersonMiddleNameProperty，中间名
     
     kABPersonPrefixProperty，前缀
     
     kABPersonSuffixProperty，后缀
     
     kABPersonNicknameProperty，昵称
     
     kABPersonFirstNamePhoneticProperty，名字汉语拼音或音标
     
     kABPersonLastNamePhoneticProperty，姓氏汉语拼音或音标
     
     q kABPersonMiddleNamePhoneticProperty，中间名汉语拼音或音标
     
     kABPersonOrganizationProperty，组织名
     
     kABPersonJobTitleProperty，头衔
     
     kABPersonDepartmentProperty，部门
     
     kABPersonNoteProperty，备注
     
     CFTypeRef ABRecordCopyValue (
     
     ABRecordRef record,
     
     ABPropertyID property
     
     );
     
     */
    static NSString *CellIdentifier = @"cell";
    
    YLAddBookTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[YLAddBookTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    //    ABRecordRef thisPerson = CFBridgingRetain([[self.listContacts objectAtIndex:indexPath.section]objectAtIndex:indexPath.row]);// ①第①行ABRecordRef thisPerson = CFBridgingRetain([self.listContacts objectAtIndex:[indexPath row]])语句是从NSArray*集合中取出一个元素，并且转化为Core Foundation类型的ABRecordRef类型。CFBridgingRelease(ABRecordCopyValue(thisPerson, kABPersonFirstNameProperty))语句是将名字属性取出来，转化为NSString*类型。最后CFRelease(thisPerson)是释放ABRecordRef对象。
    //    NSString *firstName = CFBridgingRelease(ABRecordCopyValue(thisPerson, kABPersonFirstNameProperty)); //②
    //    firstName = firstName != nil?firstName:@"";
    //
    //
    //    NSString *centerName = CFBridgingRelease(ABRecordCopyValue(thisPerson, kABPersonMiddleNameProperty)); //②
    //    centerName = centerName != nil?centerName:@"";
    //
    //    NSString *lastName =  CFBridgingRelease(ABRecordCopyValue(thisPerson, kABPersonLastNameProperty));  //③
    //
    //    lastName = lastName != nil?lastName:@"";
    //
    //    cell.textLabel.text = [NSString stringWithFormat:@"%@%@%@",lastName,centerName,firstName];
    //
    //    CFRelease(thisPerson);
    cell.labelmingzi.text = [[self.letterResultArr objectAtIndex:indexPath.section]objectAtIndex:indexPath.row];
    
    
    [cell.labelTou setPersistentBackgroundColor: [self randomColor]];
    cell.labelTou.text = [[[self.letterResultArr objectAtIndex:indexPath.section]objectAtIndex:indexPath.row] substringWithRange:NSMakeRange(0, 1)];
    
    return cell;
    
}

-(UIColor *) randomColor
{
    CGFloat hue = ( arc4random() % 256 / 256.0 ); //0.0 to 1.0
    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0,away from white
    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; //0.5 to 1.0,away from black
    return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    [self.theSearchBar resignFirstResponder];
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.theSearchBar resignFirstResponder];
    
    //点击行会有对号标记
    YLAddBookTableViewCell *oneCell = [tableView cellForRowAtIndexPath: indexPath];
//        if (oneCell.accessoryType == UITableViewCellAccessoryNone) {
//            oneCell.accessoryType = UITableViewCellAccessoryCheckmark;
//        } else{
//            oneCell.accessoryType = UITableViewCellAccessoryNone;
//        }
    NSLog(@"%@",[[self.letterResultArr objectAtIndex:indexPath.section]objectAtIndex:indexPath.row]);
    
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
